﻿<%@ Page Language="C#" AutoEventWireup="true" %>
<%@ Import Namespace= "System"%>
<%@ Import Namespace= "Microsoft.SharePoint"%>
<%@ Import Namespace= "Microsoft.SharePoint.WebControls"%>
<%@ Import Namespace= "System.IO"%>
<%@ Import Namespace= "System.Xml"%>
<%@ Import Namespace= "System.Xml.XPath"%>
<%@ Import Namespace= "System.Net"%>

<%   

    long maxRequest = 102400;
    int timeout = 3000;
    
    string query, url = String.Empty;
    XmlDocument doc;
    
    
    // length check
    if(Request.InputStream.Length > maxRequest)
    {
        Response.Write("Error: max request length reached");
        return;
    }
    // read query
    StreamReader reader = new StreamReader(Request.InputStream);
    query = reader.ReadToEnd();
    reader.Close();
    
    // extract Url
    try
    {
        doc = new XmlDocument();
        doc.InnerXml = query;

        XPathNavigator navigator = doc.CreateNavigator();
        navigator = navigator.SelectSingleNode("//WebServiceURL");
        UriBuilder builder = new UriBuilder(navigator.InnerXml);
        url = builder.Uri.AbsoluteUri;
        navigator.DeleteSelf();
        
    }
    catch (Exception ex) { Response.Write("Error: invalid request"); return; }

    
    // build request
    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
    req.Timeout = timeout;
    req.ContentType = "text/xml;charset=\"utf-8\"";
    req.Accept = "text/xml";
    req.Method = "POST";
    req.Credentials = System.Net.CredentialCache.DefaultCredentials;
    
    Stream stm = req.GetRequestStream();
    doc.Save(stm);
    stm.Close();
    


    try
    {
        WebResponse resp = req.GetResponse();
        reader = new StreamReader(resp.GetResponseStream());
        Response.Write(reader.ReadToEnd());
        reader.Close();
        
    }
    catch (Exception ex)
    {
        Response.Write("Error: Response failed");
        return;
    }
    finally
    {
        if (null != reader)
            reader.Close();
    }
    
   
       
       
       %>
